﻿using Newtonsoft.Json;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace MyOCR.Translate
{
    class SouGo_TranslateHandle : TranslateHandle
    {
        public override string GetResult()
        {
            var lst = new List<string>();
            var content = GetJson();
            dynamic json = JsonConvert.DeserializeObject(content);

            try
            {
                return string.Join("\r\n", json.translation.ToString());
            }
            catch (Exception)
            {
                return "错误码 ：" + json.errorCode + ",请检查密钥或网络状态";
            }
        }

        protected override string GetJson()
        {
            var client = new RestClient("http://fanyi.sogou.com/reventondc/api/sogouTranslate");
            var request = new RestRequest(Method.POST);
            request.AddHeader("cache-control", "no-cache");
            request.AddHeader("accept", "application/json");
            request.AddHeader("content-type", "application/x-www-form-urlencoded");
            request.AddParameter("q", need_Tslt);
            request.AddParameter("from", "auto");
            request.AddParameter("to", "zh-CHS");
            request.AddParameter("pid", Program._config.SouGou_Pid);
            request.AddParameter("salt", "1508404016012");
            request.AddParameter("sign", getSign());

            IRestResponse response = client.Execute(request);

            return response.Content;
        }

        protected override string getSign()
        {
            string sign = string.Format("{0}{1}{2}{3}", Program._config.SouGou_Pid, need_Tslt.Trim(), "1508404016012", Program._config.SouGou_Key);
            var md5 = new MD5CryptoServiceProvider();
            var result = Encoding.UTF8.GetBytes(sign);
            var output = md5.ComputeHash(result);

            return BitConverter.ToString(output).Replace("-", "").ToLower();
        }
    }
}
